<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="all" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <myTr
          v-for="(item, index) in goodList"
          :key="index"
          :cart="item"
          :index="index"
          @removeAction="removeFn"
          @addAction="addFn"
          @redAction="redFn"
          @totalChangeAction="changeFn"
        ></myTr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ grandTotal }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import myTr from "./components/myTr";
export default {
  components: {
    myTr,
  },
  methods: {
    removeFn(index) {
      this.goodList.splice(index, 1);
      this.totalArr.splice(index, 1);
    },
    addFn(index) {
      this.goodList[index].num++;
    },
    redFn(index) {
      this.goodList[index].num > 1
        ? this.goodList[index].num--
        : this.removeFn(index);
    },
    changeFn(val, index) {
      this.$set(this.totalArr, index, val);
    },
  },
  //这里效率极低，需要优化
  watch: {
    totalArr: {
      handler() {
        let sum = 0;
        this.goodList.forEach((item, index) => {
          if (item.checked) {
            sum += this.totalArr[index];
          }
        });
        this.grandTotal = sum;
      },
      immediate: true,
      deep: true,
    },
    goodList: {
      handler(newVal, oldVal) {
        let sum = 0;
        this.goodList.forEach((item, index) => {
          if (item.checked) {
            sum += this.totalArr[index];
          }
        });
        this.grandTotal = sum;
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    all: {
      get() {
        return this.goodList.every((item) => item.checked);
      },
      set(val) {
        this.goodList.forEach((item) => {
          item.checked = val;
        });
      },
    },
  },
  data() {
    return {
      totalArr: [],
      grandTotal: 10,
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: true,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: true,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
};
</script>

<style>
</style>